package com.lb.tools.lbtools.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

/**
 * @author TOSHIBA
 *<dependency>
 <groupId>org.apache.pdfbox</groupId>
 <artifactId>pdfbox-app</artifactId>
 <version>2.0.2</version>
 </dependency>

 */
//速度有点慢，一秒2-3张
public class PdfToImgUtil {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		try {
			PDF2ImagByPdfBox("G:\\BaiduYunDownload\\JAVA2网络协议内幕.pdf","C:\\Users\\TOSHIBA\\Desktop\\t\\");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("over");
		}
          System.out.println("over");
    
	}

	/**
	 * @param pdfFilePath
	 *            如 C:\\Users\\TOSHIBA\\Desktop\\Helloworld.pdf
	 * @param imaDir
	 *            如 C:\\Users\\TOSHIBA\\Desktop\\
	 */
	public static void PDF2ImagByPdfBox(String pdfFilePath, String imaDir) {

		File file = new File(pdfFilePath);
		if (!pdfFilePath.endsWith("pdf") && !pdfFilePath.endsWith("PDF")) {
			throw new RuntimeException("不是pdf文件");
		}

		if (imaDir.charAt(imaDir.length() - 1) != '\\') {
			imaDir += "\\";
		}
		PDDocument doc=null;
		try {
	
			 doc = PDDocument.load(file);
			PDFRenderer renderer = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			for (int i = 0; i < pageCount; i++) {
		        BufferedImage image = renderer.renderImageWithDPI(i, 296);
				ImageIO.write(image, "PNG", new File(imaDir + i + ".png"));
				System.out.println("转换页数" + i+ "----- "+ "总共页数"+ pageCount);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null!=doc){
					doc.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

	}

}
